package com.lgCore.controller;/**
 * Created by by on 2020/11/19 14:11
 */

import com.alibaba.fastjson.JSON;
import com.google.protobuf.ByteString;
import com.lgCore.client.NettyClientBootstrap;
import com.lgCore.common.ClientSession;
import com.lgCore.protoModel.ProtoMsg;
import com.lgCore.queue.ClientResultQueue;
import com.lgCore.util.ByteObjUtil;
import com.lgCore.util.ProtoByteUtil;
import io.netty.channel.Channel;
import io.netty.util.Attribute;

import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @program: sxreader_rpc
 * @author: ligang
 * @create: 2020-11-19 14:11
 */
public class ClientBootstrap {
    static String ip = "127.0.0.1";
    static int port = 9999;
    public static NettyClientBootstrap bootstrap = null;

    public static void send() throws Exception {
        Attribute<ClientSession> constantsAttributeKey = bootstrap.getChannel().attr(ClientSession.SESSION_KEY);
        ClientSession clientSession = constantsAttributeKey.get();
        Channel channel = bootstrap.getChannel();
        ProtoMsg.Message.Builder requestMessage = ProtoMsg.Message.newBuilder();
        String uuid = UUID.randomUUID().toString();
        //登录请求
        ProtoMsg.RpcRequest.Builder rpcRequest = ProtoMsg.RpcRequest.newBuilder();
        rpcRequest.setRequestId(uuid);
        rpcRequest.setClientId(clientSession.getClientId());
        rpcRequest.setServiceName("appService");
        Object[] objects = new Object[2];
        objects[0] = "111111";
        objects[1] = "111111";

//        rpcRequest.setRequestObjects(JSON.toJSONString(objects));
        rpcRequest.setRequestObjects( ByteString.copyFrom(ByteObjUtil.objToBytes(objects)));

        rpcRequest.setType(ProtoMsg.HeadType.RPC_REQUEST);
        requestMessage.setRpcRequest(rpcRequest);

        //记录到队列
        LinkedBlockingQueue<Object> responseQueue = new LinkedBlockingQueue<Object>(1);

        ClientResultQueue.putResponse(uuid, responseQueue);
        channel.writeAndFlush(ProtoByteUtil.protoToByte(requestMessage));

        //查询队列结果
        Object result2 = responseQueue.poll(
                30L,
                TimeUnit.SECONDS);
//        System.out.println("拿到结果" + result2);
    }
}
